package com.hsq.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.hsq.spzx.common.exception.HsqException;
import com.hsq.spzx.manager.listener.ExcelListener;
import com.hsq.spzx.manager.mapper.user.CategoryMapper;
import com.hsq.spzx.manager.service.CategoryService;
import com.hsq.spzx.model.entity.product.Category;
import com.hsq.spzx.model.vo.common.ResultCodeEnum;
import com.hsq.spzx.model.vo.product.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hsq
 * @date 2025-06-07 下午2:00
 */
@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findByParentId(Long parentId) {
        // 根据分类id查询它下面的所有的子分类数据
        List<Category> categoryList = categoryMapper.selectByParentId(parentId);
        if (!CollectionUtils.isEmpty(categoryList)) {
            for (Category category: categoryList) {
                // 查询该分类下子分类的数量
                int count = categoryMapper.countByParentId(category.getId());
                if (count > 0) {
                    category.setHasChildren(true);
                } else {
                    category.setHasChildren(false);
                }
            }
        }
        return categoryList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try{
            // 设置响应结果类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类数据", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            // 查询数据库中的数据
            List<Category> categoryList = categoryMapper.selectAll();

            List<CategoryExcelVo> categoryExcelVos = new ArrayList<>();
            // 将从数据库中查询到的Category对象转换成CategoryExcelVo对象
            for(Category category : categoryList) {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo, CategoryExcelVo.class);
                categoryExcelVos.add(categoryExcelVo);
            }
            // 写出数据到浏览器端
            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class)
                    .sheet("分类数据")
                    .doWrite(categoryExcelVos);
        }catch (Exception e) {
            log.error(e.getMessage());
            throw new HsqException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public void importData(MultipartFile multipartFile) {
        //创建监听器对象，传递mapper对象
        ExcelListener<CategoryExcelVo> excelListener = new ExcelListener<>(categoryMapper);
        try{
            EasyExcel.read(multipartFile.getInputStream(), CategoryExcelVo.class, excelListener)
                    .sheet().doRead();
        }catch (IOException e) {
            log.error(e.getMessage());
            throw new HsqException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
